//
//  SearchViewController.m
//  体育商城
//
//  Created by  on 2022/9/25.
//

#import "SearchViewController.h"
#import "SearchCell.h"
#import "GoodsCell.h"
#define recordKey @"recordKey"
@interface SearchViewController ()<UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UIView *bgView;
@property (strong, nonatomic) IBOutlet UIView *nodataView;
@property (strong, nonatomic) IBOutlet UICollectionView *collection;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *collectionTop;
@property (nonatomic,strong) BaseTextField *search;
@property (nonatomic,strong) UIButton *rightBtn;
@property (nonatomic,assign) BOOL isrecord;
@property (nonatomic,strong) NSMutableArray * recordArray;
@property (nonatomic,strong) NSMutableArray <Goods *>* array;
@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.search endEditing:YES];
}
- (void)initUI{
    NSArray *array = [[NSUserDefaults standardUserDefaults] valueForKey:recordKey];
    if (array == nil || array.count <= 0) {
        array = @[LS(@"全部"),LS(@"球鞋"),LS(@"篮球"),LS(@"足球"),LS(@"足球衫")];
    }
    self.recordArray = [NSMutableArray arrayWithArray:array];
    self.isrecord = YES;
    self.rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightBtn.tag = 201;
    self.rightBtn.frame = CGRectMake(0, StuBarHight + 5, 60, 34);
    [self.rightBtn addTarget:self action:@selector(actionForBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.rightBtn setTitleColor:[UIColor colorHex:@"#1A1A1A"] forState:UIControlStateNormal];
    [self.rightBtn setTitle:LS(@"取消") forState:UIControlStateNormal];
    [self.rightBtn setTitle:LS(@"确定") forState:UIControlStateSelected];
    
    self.rightBtn.font = [UIFont systemFontOfSize:12];
    UIBarButtonItem *item =[[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
    self.navigationItem.rightBarButtonItem = item;
    
    
    UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"搜索"]];
    image.frame = CGRectMake(16, 10, 24, 24);
    self.search = [[BaseTextField alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 100, 40)];
    self.search.delegate = self;
    self.search.leftView = image;
    self.search.leftViewMode = UITextFieldViewModeAlways;
    self.search.backgroundColor = [UIColor colorHex:@"#FAFAFA" alpha:1];
    self.search.placeholder = LS(@"搜索商品");
    self.search.cornerRadius = 5;
    self.navigationItem.titleView = self.search;
    
    [self.collection registerNib:[SearchCell nib] forCellWithReuseIdentifier:[SearchCell ID]];
    [self.collection registerNib:[GoodsCell nib] forCellWithReuseIdentifier:[GoodsCell ID]];
}
- (void)actionForBtn:(UIButton *)sender{
    if (sender.selected) {
        self.isrecord = NO;
        if ([self.recordArray containsObject:self.search.text] == NO) {
            [self.recordArray addObject:self.search.text];
            [self saveRecord];
        }
        [self loadData];
    }else{
        self.isrecord = YES;
        [self.collection reloadData];
    }
    
}
- (void)saveRecord{
    [[NSUserDefaults standardUserDefaults] setValue:self.recordArray forKey:recordKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self.collection reloadData];
}
- (void)setRecordArray:(NSMutableArray *)recordArray{
    _recordArray = recordArray;
    [self.collection reloadData];
}
- (void)setArray:(NSMutableArray<Goods *> *)array{
    _array = array;
    if (array && array.count > 0) {
        self.isrecord = NO;
        self.nodataView.hidden = YES;
        self.collectionTop.constant = -25;
    }else{
        self.isrecord = YES;
        [self.search endEditing:YES];
        self.collectionTop.constant = 0;
        self.nodataView.hidden = NO;
    }
    [self.collection reloadData];
}
- (void)loadData{
    if (self.search.text.length<= 0) {
        return;
    }
    [Toast startHud:LS(@"搜索中...")];
    [GoodsTool findAll:self.search.text block:^(NSMutableArray<Goods *> * _Nonnull result) {
        [Toast startHud:LS(@"搜索中...") stopTime:1 handle:nil];
        self.array = result;
    }];
}
- (void)actionForTap{
    [self.search endEditing:YES];
}
#pragma mark - UITextFieldDelegate
//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
//    self.isrecord = YES;
//    self.rightBtn.selected = textField.text.length > 0;
//    self.collectionTop.constant = 0;
//    [self.collection reloadData];
//    return YES;
//}

- (void)textFieldDidChangeSelection:(UITextField *)textField{
    self.rightBtn.selected = textField.text.length > 0;
    self.isrecord = textField.text.length <= 0;
    self.nodataView.hidden = textField.text.length <= 0;
    [self.collection reloadData];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.isrecord ? self.recordArray.count : self.array.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    WS(self)
    if (self.isrecord) {
        SearchCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[SearchCell ID] forIndexPath:indexPath];
        cell.title.text = LS(self.recordArray[indexPath.row]);
        cell.block = ^{
            [weakself.recordArray removeObjectAtIndex:indexPath.row];
            [weakself saveRecord];
        };
        return  cell;
    }
    GoodsCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[GoodsCell ID] forIndexPath:indexPath];
    cell.model = self.array[indexPath.row];
    return  cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isrecord) {
        NSString *string = self.recordArray[indexPath.row];
        self.search.text = LS(string);
        [self.recordArray removeObjectAtIndex:(int)indexPath.row];
        [self.recordArray insertObject:string atIndex:0];
        self.rightBtn.selected = YES;
        [self.array removeAllObjects];
        [self.search becomeFirstResponder];
        [self actionForBtn:self.rightBtn];
        [self saveRecord];
    }else{
        BuyViewController *vc = [[BuyViewController alloc] init];
        vc.model = self.array[indexPath.row];
        [[self currentVC].navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isrecord) {
        CGFloat w = (SCREEN_WIDTH - 10 * 4) / 3.0;
        w = MIN(ceil(w), 100);
        return CGSizeMake(w, 32);
    }
    CGFloat w = (SCREEN_WIDTH - 20 * 3) / 2;
    CGFloat h = 240 / 168.0 * w;
    return CGSizeMake(w, h);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return  UIEdgeInsetsMake(20, 20, 20, 20);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return self.isrecord ? 10 : 20;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return self.isrecord ? 10 : 20;
}

@end
